package imPro;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author Ragnar
 */
public class BeagleClient extends JPanel implements Runnable
{
    private ObjectOutputStream output;
    private ObjectInputStream input;
    private Image src;
    private Socket socket;
    
    public BeagleClient()
    {
        this.src = null;
        String ip = "158.38.192.179";
        //String ip = "localhost";
        int port = 4444;
        try
        {
            socket = new Socket(ip, port);
            System.out.println("Connected to " + ip + " on port " + port + "!");
        }
        catch (IOException e) {}
        Thread t = new Thread(this);
        t.start();
    }
    
    public void run()
    {        
        try
        {
            input = new ObjectInputStream(socket.getInputStream());
            while (true)
            {
                Thread.sleep(50);
                System.out.println("Reading object");
                //Object im = input.readObject();
                src = ImageIO.read(input);
                System.out.println("Object read");
                System.out.println("Image set");
                this.repaint();
            }
        }
        catch (InterruptedException e) {}
        catch (IOException e) {}
           // catch (ClassNotFoundException e) {}
    }
    
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        if (src != null)
        {
            ((Graphics2D)g).drawImage(src, null, this);
        }
    }
    
    public static void main(String[] args)
    {
        BeagleClient bc = new BeagleClient();
        JFrame f = new JFrame();
        Container c = f.getContentPane();
        bc.setBounds(0, 0, 320, 240);
        c.add(bc);
        f.setMinimumSize(new Dimension(400, 300));
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}
